﻿create procedure [dbo].[usp_WorkItemInsert]
	@Id int
	, @TeamFoundationServerId int
	, @Uri nvarchar(1024)
as

begin try
	
	begin transaction
	
		if not exists(select * from [dbo].[WorkItem] where [Id] = @Id and
			                                               [TeamFoundationServerId] = @TeamFoundationServerId and 
				                                           [Uri] = @Uri)
			begin
										                              
				insert [dbo].[WorkItem]
				(
					[Id]
					, [TeamFoundationServerId]
					, [Uri]				
			    )
				values
				(
					@Id
					, @TeamFoundationServerId
					, @Uri
				)
				
				select WorkItemId, ConcurrencyId, Created, Updated from [dbo].[WorkItem] where @@rowcount > 0 and WorkItemId = scope_identity()
			
			end
			
		else
			
			begin
			
				select WorkItemId, ConcurrencyId, Created, Updated from [dbo].[WorkItem] where [Id] = @Id and
			                                                                                   [TeamFoundationServerId] = @TeamFoundationServerId and 
				                                                                               [Uri] = @Uri
			end
	
	commit transaction

end try
	
begin catch
	if @@trancount > 0
	begin
		rollback transaction;
	end
	execute [dbo].[usp_SqlErrorInsert]
end catch


